#include <iostream>
#include <memory>

#include "Log.hpp"
#include "Reactor.hpp"
#include "Listener.hpp"
#include "HandlerConnection.hpp"
#include "PackageParse.hpp"

using namespace log_ns;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " local-port" << std::endl;
        exit(0);
    }
    uint16_t port = std::stoi(argv[1]);
    InetAddr localAddr("0.0.0.0", port);

    PackageParse parse;

    // 处理新链接
    Listener listener(port);

    // 处理普通sockfd
    HandlerConnection handlers(std::bind(&PackageParse::Excute, &parse, std::placeholders::_1));

    // 主模块，事件派发
    std::unique_ptr<Reactor> R = std::make_unique<Reactor>();

    R->SetOnConnect(std::bind(&Listener::Accepter, &listener, std::placeholders::_1));
    R->SetOnNormalHandler(std::bind(&HandlerConnection::HandlerRecver, &handlers, std::placeholders::_1),
                          std::bind(&HandlerConnection::HandlerSender, &handlers, std::placeholders::_1),
                          std::bind(&HandlerConnection::HandlerExcepter, &handlers, std::placeholders::_1));
    R->AddConnection(listener.ListenSockfd(), EPOLLIN | EPOLLET, ListenConnection, localAddr);
    R->Dispatcher();
    return 0;
}